# fileName:mouse.py
# encoding:utf-8
# usage:监听鼠标右键，获取剪切板内容，查询csv中是否含有，并提示
# Use:双击运行
# ChangeLog:
#   2022/02/02  words.csv修改了数据列
import csv
import re
import subprocess
from pynput import mouse
# pip3 install -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com pyperclip
import pyperclip

def getWords(filePath, newWord):
    with open(filePath, mode='r', encoding='gbk', newline='') as f:
        # 此处读取到的数据是将每行数据当做列表返回的
        reader = csv.reader(f)
        # 此时输出的是一行行的列表
        for row in reader:
            try:
                if newWord == row[1]:
                    return row[2]
            except print(0):
                break
        return ''
    
    
# 匹配全字母
pattern = re.compile(r"^[A-Za-z]+$")
# 上一个字符串
last_str = ''
def on_click(x, y, button, pressed):
    if not pressed:
        return False
    elif str(button) == 'Button.right':
        print('点击了鼠标右键')
        now_str = pyperclip.paste().strip()
        print('now_str:',now_str)
        global last_str
        if last_str == now_str:
            print('已经提示过不再提示了')
            return ''
        if re.search(pattern, now_str):
            print('纯字母：',now_str)
            last_str = now_str
            now_str_chinese = getWords('words.csv', now_str)
            if now_str_chinese != '':
                cmd_ = 'notification  --title '+'"'+now_str+'" --message "'+now_str_chinese+'" --action "打开浏览器->看百度翻译" --action-arg "https://fanyi.baidu.com/?aldtype=16047#en/zh/'+now_str+'"'
                print(cmd_)
                subprocess.Popen(cmd_, stdout = subprocess.PIPE, creationflags = subprocess.CREATE_NO_WINDOW)
            else:
                cmd_ = 'notification --title '+'"'+now_str+'" --message "这个单词没记录" --action "打开浏览器->看百度翻译" --action-arg "https://fanyi.baidu.com/?aldtype=16047#en/zh/'+now_str+'"'
                print(cmd_)
                subprocess.Popen(cmd_, stdout = subprocess.PIPE, creationflags = subprocess.CREATE_NO_WINDOW)
        else:
            print('不是纯字母')


while True:
    with mouse.Listener( on_click = on_click) as listener:
        listener.join()
            